(function(){
    //蛇的构造函数
    function Snake (options){
        options = options ||{};
        this.width = options.width || 20;
        this.height = options.height ||20;
        this.body = [
            {x:3,y:2,color:'red'},
            {x:2,y:2,color:'blue'},
            {x:1,y:2,color:'blue'}
        ];
        this.direction = options.direction || 'right';
        
    }
    //创建蛇对象
    // var snake = new Snake();
    //定义数组存储蛇节
    var elements = [];
    //定义蛇的变量，存储，然后删除
   
     //蛇移动
     Snake.prototype.moveSnake = function(food,map){
        //蛇身移动
       for(var i=this.body.length-1 ; i>0;i--){
           this.body[i].x=this.body[i-1].x;
           this.body[i].y=this.body[i-1].y;
       }
       //蛇头移动
       var head = this.body[0];
       switch(this.direction){
           case 'left':
                head.x-=1;
                break;
           case 'right':
                head.x+=1;
                break;
           case 'top':
                head.y-=1;
                break;
           case 'bottom':
                head.y+=1;
                break;
            
       }
      
    var headX = head.x ;
    var headY = head.y ;
    if (headX === food.x && headY === food.y) {
      // 让蛇增加一节
      // 获取蛇的最后一节
      var last = this.body[this.body.length - 1];
      this.body.push({
        x: last.x,
        y: last.y,
        color: last.color
      })

      // 随机在地图上重新生成食物
      food.render(map);
    }
    }
    //渲染蛇到页面上
    Snake.prototype.render = function(map){

        removeSnake(map);
        // this.moveSnake()
        for(var i=0 ; i<this.body.length ; i++){
            var divSnake = document.createElement('div');
            divSnake.style.position = 'absolute';
            divSnake.style.width = this.width +'px';
            divSnake.style.height = this.height +'px';
            divSnake.style.left = this.body[i].x*this.width +'px';
            divSnake.style.top = this.body[i].y*this.height +'px';
            divSnake.style.backgroundColor = this.body[i].color;
           
           elements.push(divSnake);
            map.appendChild(divSnake); 
            
        }
    }
   
    //删除蛇
    function removeSnake (map){
         
          var i = elements.length-1;
          while(elements.length!=0){
             //删除蛇的div
            map.removeChild(elements[i]);
         
        //删除蛇的记录
        elements.splice(i,1);
        i--; 
    }
      
    }

    
    //测试
    
    
    // var timer = setInterval(function(){
    
    // snake.render(document.getElementById('map'));
    // snake.moveSnake();
    // // snake.moveSnake();
    // },1000);

window.Snake = Snake;


})();